package com.aerospace.distributed;

import org.springframework.data.redis.connection.RedisConnection;

import java.util.Date;

/**
 * @Author: Aerospace
 * @Date: 2021/5/10 17:00
 * @Description: Dream begins
 */
public class RedisLock {

    public boolean tryLock(RedisConnection conn){
        long nowtime = System.currentTimeMillis();
        long expireTime = nowtime+1000;
        if (conn.setNX("mykey".getBytes(),String.valueOf(expireTime).getBytes())==true){
            conn.expire("mykey".getBytes(),1000);
            return true;
        }else {
            long oldVal = Long.parseLong(conn.get("mykey".getBytes()).toString());
            if(oldVal!=0&&oldVal<nowtime){
                long currentval = Long.parseLong(conn.getSet("mykey".getBytes(),String.valueOf(expireTime).getBytes()).toString());
                if (oldVal == currentval){
                    conn.expire("mykey".getBytes(),1000);
                    conn.setEx("mykey".getBytes(),1000,"mykey".getBytes());
                    return true;
                }
            }
            return false;
        }
    }
}
